package com.logos.musicframe.ui.javafx;

import com.logos.musicframe.controller.PlaylistCollectedController;
import com.logos.musicframe.controller.PlaylistController;
import com.logos.musicframe.req.PlaylistReq;
import com.logos.musicframe.resp.PlaylistResp;
import com.logos.musicframe.resp.SongsResp;
import com.logos.musicframe.result.Result;
import com.logos.musicframe.utils.JavaFxMusicPlayer;
import com.logos.musicframe.utils.SpringContextUtil;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.util.Duration;
import javafx.scene.control.Alert;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author logos
 * date 2025/6/15 10:00
 * @version v1.0
 * @Package com.logos.musicframe.ui.javafx
 */
@Slf4j
public class PlaylistUi {
    
    private PlaylistController playlistController = SpringContextUtil.getBean(PlaylistController.class);
    private JavaFxMusicPlayer player;
    
    // 回调接口，用于通知主UI更新当前歌曲
    private PlaylistSelectedCallback playlistSelectedCallback;
    
    // 歌单列表刷新回调
    private PlaylistRefreshCallback playlistRefreshCallback;
    
    // 当前选中的歌单
    private PlaylistResp currentPlaylist;
    
    // 已移除isCollected变量，因为收藏功能已在"发现歌单"页面实现
    
    // UI组件
    private VBox detailContainer;
    
    // 控制是否自动加载第一个歌单
    private boolean autoLoadFirstPlaylist = true;
    
    public PlaylistUi(JavaFxMusicPlayer player, PlaylistSelectedCallback playlistSelectedCallback, PlaylistRefreshCallback playlistRefreshCallback) {
        this.player = player;
        this.playlistSelectedCallback = playlistSelectedCallback;
        this.playlistRefreshCallback = playlistRefreshCallback;
    }
    
    /**
     * 创建歌单页面
     */
    public VBox createPlaylistPage() {
        VBox mainContainer = new VBox(10);
        mainContainer.setPadding(new Insets(10));
        
        // 标题
        HBox headerBox = new HBox(10);
        headerBox.setAlignment(Pos.CENTER_LEFT);
        
        Label titleLabel = new Label("我的歌单");
        titleLabel.setStyle("-fx-font-size: 24px; -fx-font-weight: bold;");
        
        headerBox.getChildren().add(titleLabel);
        
        // 歌单详情容器
        detailContainer = new VBox(10);
        detailContainer.setPadding(new Insets(10));
        detailContainer.setAlignment(Pos.TOP_CENTER);
        VBox.setVgrow(detailContainer, Priority.ALWAYS);
        
        // 初始提示信息
        Label placeholderLabel = new Label("请选择一个歌单");
        placeholderLabel.setStyle("-fx-font-size: 16px; -fx-text-fill: #999;");
        detailContainer.getChildren().add(placeholderLabel);
        
        // 加载歌单列表（后台）
        loadPlaylistsInBackground();
        
        // 添加到主容器
        mainContainer.getChildren().addAll(headerBox, new Separator(), detailContainer);
        
        return mainContainer;
    }
    
    /**
     * 在后台加载歌单列表
     */
    private void loadPlaylistsInBackground() {
        // 异步加载歌单
        new Thread(() -> {
            List<PlaylistResp> playlists = new ArrayList<>();
            try {
                Result<List<PlaylistResp>> result = playlistController.queryByUserId();
                if (result.isSuccess() && result.getData() != null) {
                    playlists = result.getData();
                }
            } catch (Exception e) {
                log.error("加载歌单失败", e);
            }
            
            // 最终结果
            List<PlaylistResp> finalPlaylists = playlists;
            
            // 在JavaFX线程中更新UI
            Platform.runLater(() -> {
                if (!finalPlaylists.isEmpty()) {
                    // 只有在autoLoadFirstPlaylist为true且当前没有选中歌单时，才自动加载第一个歌单
                    if (autoLoadFirstPlaylist && currentPlaylist == null) {
                        showPlaylistDetailInternal(finalPlaylists.get(0));
                    }
                } else {
                    // 如果没有歌单且当前没有显示任何歌单，则显示空提示
                    if (currentPlaylist == null) {
                        Label emptyLabel = new Label("暂无歌单，点击上方按钮创建");
                        emptyLabel.setStyle("-fx-text-fill: #999; -fx-font-style: italic;");
                        detailContainer.getChildren().clear();
                        detailContainer.getChildren().add(emptyLabel);
                    }
                }
            });
        }).start();
    }
    
    /**
     * 显示歌单详情
     */
    private void showPlaylistDetailInternal(PlaylistResp playlist) {
        detailContainer.getChildren().clear();
        
        // 显示加载指示器
        ProgressIndicator loading = new ProgressIndicator();
        loading.setMaxSize(50, 50);
        detailContainer.getChildren().add(loading);
        
        // 异步加载歌单详情
        new Thread(() -> {
            try {
                // 重新查询歌单详情以获取最新数据，特别是歌曲列表
                PlaylistResp updatedPlaylist = playlist;
                if (playlist.getId() != null) {
                    Result<PlaylistResp> result = playlistController.queryById(playlist.getId());
                    if (result.isSuccess() && result.getData() != null) {
                        updatedPlaylist = result.getData();
                        // 更新当前选中的歌单
                        currentPlaylist = updatedPlaylist;
                        log.info("获取歌单详情成功，歌曲数量: {}", 
                            updatedPlaylist.getSongsRespList() != null ? updatedPlaylist.getSongsRespList().size() : 0);
                    } else {
                        log.error("获取歌单详情失败: {}", result.getMessage());
                    }
                }
                
                // 最终使用的歌单对象
                final PlaylistResp finalPlaylist = updatedPlaylist;
                
                // 在JavaFX线程中更新UI
                Platform.runLater(() -> {
                    detailContainer.getChildren().clear();
                    
                    // 歌单信息头部
                    HBox headerBox = createPlaylistHeader(finalPlaylist);
                    
                    // 歌曲列表
                    VBox songsBox = createSongsListView(finalPlaylist);
                    
                    detailContainer.getChildren().addAll(headerBox, new Separator(), songsBox);
                });
            } catch (Exception e) {
                log.error("加载歌单详情异常", e);
                
                // 出现异常时，仍然尝试显示原始歌单信息
                Platform.runLater(() -> {
                    detailContainer.getChildren().clear();
                    
                    // 歌单信息头部
                    HBox headerBox = createPlaylistHeader(playlist);
                    
                    // 歌曲列表
                    VBox songsBox = createSongsListView(playlist);
                    
                    detailContainer.getChildren().addAll(headerBox, new Separator(), songsBox);
                });
            }
        }).start();
    }
    
    /**
     * 创建歌单头部信息
     */
    private HBox createPlaylistHeader(PlaylistResp playlist) {
        HBox headerBox = new HBox(20);
        headerBox.setPadding(new Insets(15));
        headerBox.setAlignment(Pos.CENTER_LEFT);
        
        // 歌单封面
        ImageView coverImage = new ImageView();
        coverImage.setFitWidth(150);
        coverImage.setFitHeight(150);
        
        // 设置封面图片
        if (playlist.getCoverUrl() != null && !playlist.getCoverUrl().isEmpty()) {
            coverImage.setImage(new Image(playlist.getCoverUrl()));
        } else {
            coverImage.setImage(new Image("static/default-cover.png"));
        }
        
        // 添加圆角和阴影效果
        coverImage.setStyle("-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.3), 10, 0, 0, 5);");
        
        // 歌单信息
        VBox infoBox = new VBox(10);
        infoBox.setAlignment(Pos.CENTER_LEFT);
        
        Label typeLabel = new Label("歌单");
        typeLabel.setStyle("-fx-font-size: 14px; -fx-text-fill: #666;");
        
        Label nameLabel = new Label(playlist.getName());
        nameLabel.setStyle("-fx-font-size: 28px; -fx-font-weight: bold;");
        
        Label descLabel = new Label(playlist.getDescription());
        descLabel.setStyle("-fx-font-size: 14px; -fx-text-fill: #666;");
        descLabel.setWrapText(true);
        
        Label createTimeLabel = new Label("创建于: " + playlist.getCreateTime());
        createTimeLabel.setStyle("-fx-font-size: 12px; -fx-text-fill: #999;");
        
        // 歌曲数量
        int songCount = playlist.getSongsRespList() != null ? playlist.getSongsRespList().size() : 0;
        Label countLabel = new Label("共" + songCount + "首歌曲");
        countLabel.setStyle("-fx-font-size: 14px; -fx-text-fill: #666;");
        
        infoBox.getChildren().addAll(typeLabel, nameLabel, descLabel, createTimeLabel, countLabel);
        
        // 操作按钮区
        VBox actionBox = new VBox(10);
        actionBox.setAlignment(Pos.CENTER);
        
        Button playAllButton = new Button("播放全部");
        playAllButton.setStyle("-fx-background-color: #1db954; -fx-text-fill: white; -fx-font-weight: bold; -fx-padding: 10 20;");
        playAllButton.setOnAction(e -> {
            if (playlist.getSongsRespList() != null && !playlist.getSongsRespList().isEmpty()) {
                // 播放第一首歌曲
                SongsResp firstSong = playlist.getSongsRespList().get(0);
                if (playlistSelectedCallback != null) {
                    playlistSelectedCallback.onPlaylistSelected(playlist);
                }
                player.play(firstSong.getFilePath());
            }
        });
        
        Button editButton = new Button("编辑歌单");
        editButton.setStyle("-fx-background-color: transparent; -fx-border-color: #999; -fx-text-fill: #666;");
        editButton.setOnAction(e -> {
            // TODO: 实现编辑歌单功能
        });
        
        // 已移除收藏/取消收藏按钮，因为在"发现歌单"页面已实现此功能
        
        actionBox.getChildren().addAll(playAllButton, editButton);
        
        // 添加到头部容器
        headerBox.getChildren().addAll(coverImage, infoBox, actionBox);
        HBox.setHgrow(infoBox, Priority.ALWAYS);
        
        return headerBox;
    }
    
    /**
     * 创建歌曲列表视图
     */
    private VBox createSongsListView(PlaylistResp playlist) {
        VBox songsBox = new VBox(5);
        VBox.setVgrow(songsBox, Priority.ALWAYS);
        
        // 表头
        HBox headerRow = new HBox(10);
        headerRow.setPadding(new Insets(10, 5, 10, 5));
        headerRow.setStyle("-fx-background-color: #f5f5f5; -fx-background-radius: 5;");
        
        Label indexHeader = new Label("#");
        indexHeader.setPrefWidth(30);
        indexHeader.setStyle("-fx-font-weight: bold;");
        
        Label titleHeader = new Label("歌曲");
        HBox.setHgrow(titleHeader, Priority.ALWAYS);
        titleHeader.setPrefWidth(250);
        titleHeader.setStyle("-fx-font-weight: bold;");
        
        Label artistHeader = new Label("歌手");
        artistHeader.setPrefWidth(150);
        artistHeader.setStyle("-fx-font-weight: bold;");
        
        Label albumHeader = new Label("专辑");
        albumHeader.setPrefWidth(180);
        albumHeader.setStyle("-fx-font-weight: bold;");
        
        Label durationHeader = new Label("时长");
        durationHeader.setPrefWidth(60);
        durationHeader.setAlignment(Pos.CENTER_RIGHT);
        durationHeader.setStyle("-fx-font-weight: bold;");
        
        // 添加操作列
        Label actionHeader = new Label("操作");
        actionHeader.setPrefWidth(120);
        actionHeader.setAlignment(Pos.CENTER);
        actionHeader.setStyle("-fx-font-weight: bold;");
        
        headerRow.getChildren().addAll(indexHeader, titleHeader, artistHeader, albumHeader, durationHeader, actionHeader);
        
        // 歌曲列表
        VBox songsList = new VBox(1);
        ScrollPane scrollPane = new ScrollPane(songsList);
        scrollPane.setFitToWidth(true);
        scrollPane.setStyle("-fx-background-color: transparent;");
        VBox.setVgrow(scrollPane, Priority.ALWAYS);
        
        // 添加歌曲行
        if (playlist.getSongsRespList() != null && !playlist.getSongsRespList().isEmpty()) {
            for (int i = 0; i < playlist.getSongsRespList().size(); i++) {
                SongsResp song = playlist.getSongsRespList().get(i);
                songsList.getChildren().add(createSongRow(song, i + 1));
            }
        } else {
            Label emptyLabel = new Label("该歌单暂无歌曲");
            emptyLabel.setStyle("-fx-text-fill: #999; -fx-font-style: italic;");
            emptyLabel.setPadding(new Insets(20, 0, 0, 0));
            emptyLabel.setAlignment(Pos.CENTER);
            songsList.getChildren().add(emptyLabel);
        }
        
        songsBox.getChildren().addAll(headerRow, scrollPane);
        
        return songsBox;
    }
    
    /**
     * 创建单行歌曲
     */
    private HBox createSongRow(SongsResp song, int index) {
        HBox row = new HBox(10);
        row.setPadding(new Insets(10, 5, 10, 5));
        row.setAlignment(Pos.CENTER_LEFT);
        
        // 鼠标悬停效果
        row.setOnMouseEntered(e -> row.setStyle("-fx-background-color: #f0f0f0;"));
        row.setOnMouseExited(e -> row.setStyle("-fx-background-color: transparent;"));
        
        // 单击显示在播放栏，双击播放
        row.setOnMouseClicked(e -> {
            // 单击时，更新当前歌曲信息到播放栏
            if (e.getClickCount() == 1) {
                if (playlistSelectedCallback != null) {
                    // 通过回调通知主UI更新当前歌曲
                    playlistSelectedCallback.onSongSelected(song);
                }
            }
            // 双击时，播放歌曲
            else if (e.getClickCount() == 2) {
                player.play(song.getFilePath());
            }
        });
        
        // 序号
        Label indexLabel = new Label(String.valueOf(index));
        indexLabel.setPrefWidth(30);
        indexLabel.setStyle("-fx-text-fill: #999;");
        
        // 歌曲标题
        HBox titleBox = new HBox(10);
        titleBox.setAlignment(Pos.CENTER_LEFT);
        titleBox.setPrefWidth(250);
        
        ImageView songCover = new ImageView();
        songCover.setFitWidth(40);
        songCover.setFitHeight(40);
        
        if (song.getPicture() != null && !song.getPicture().isEmpty()) {
            songCover.setImage(new Image(song.getPicture()));
        } else {
            songCover.setImage(new Image("static/default-song.png"));
        }
        
        VBox songInfoBox = new VBox(3);
        
        Label titleLabel = new Label(song.getTitle());
        titleLabel.setStyle("-fx-font-weight: bold;");
        
        songInfoBox.getChildren().add(titleLabel);
        
        titleBox.getChildren().addAll(songCover, songInfoBox);
        HBox.setHgrow(titleBox, Priority.ALWAYS);
        
        // 歌手
        Label artistLabel = new Label(song.getArtist());
        artistLabel.setPrefWidth(150);
        
        // 专辑
        Label albumLabel = new Label(song.getAlbum() != null ? song.getAlbum() : "-");
        albumLabel.setPrefWidth(180);
        
        // 时长
        Label durationLabel = new Label(formatDuration(song.getDuration()));
        durationLabel.setPrefWidth(60);
        durationLabel.setAlignment(Pos.CENTER_RIGHT);
        
        // 操作按钮
        HBox actionBox = new HBox(10);
        actionBox.setAlignment(Pos.CENTER);
        actionBox.setPrefWidth(120);
        
        // 添加到歌单按钮
        Button addToPlaylistButton = new Button();
        addToPlaylistButton.setStyle("-fx-background-color: transparent;");
        ImageView addIcon = new ImageView(new Image("static/add-to-playlist.png", 20, 20, true, true));
        addToPlaylistButton.setGraphic(addIcon);
        addToPlaylistButton.setTooltip(new Tooltip("添加到其他歌单"));
        
        // 添加点击事件
        addToPlaylistButton.setOnAction(e -> {
            // 调用主UI中的添加到歌单对话框
            try {
                MainMusicPlayerUi mainUI = SpringContextUtil.getBean(MainMusicPlayerUi.class);
                mainUI.showAddToPlaylistDialog(song);
            } catch (Exception ex) {
                log.error("获取MainMusicPlayerUi实例失败", ex);
                // 显示错误提示
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("错误");
                alert.setHeaderText(null);
                alert.setContentText("无法添加歌曲到歌单，请稍后再试");
                alert.showAndWait();
            }
        });
        
        actionBox.getChildren().add(addToPlaylistButton);
        
        row.getChildren().addAll(indexLabel, titleBox, artistLabel, albumLabel, durationLabel, actionBox);
        
        return row;
    }
    
    /**
     * 格式化时长
     */
    private String formatDuration(Integer seconds) {
        if (seconds == null) {
            return "--:--";
        }
        int minutes = seconds / 60;
        int remainingSeconds = seconds % 60;
        return String.format("%02d:%02d", minutes, remainingSeconds);
    }
    
    /**
     * 显示创建歌单对话框
     * 修改为public，允许外部调用
     */
    public void showCreatePlaylistDialog() {
        Stage dialog = new Stage();
        dialog.initModality(Modality.APPLICATION_MODAL);
        dialog.setTitle("创建歌单");
        dialog.setWidth(400);
        dialog.setHeight(450);
        
        VBox content = new VBox(15);
        content.setPadding(new Insets(20));
        
        // 歌单名称
        Label nameLabel = new Label("歌单名称:");
        TextField nameField = new TextField();
        nameField.setPromptText("请输入歌单名称");
        
        // 歌单描述
        Label descLabel = new Label("歌单描述:");
        TextArea descArea = new TextArea();
        descArea.setPromptText("请输入歌单描述");
        descArea.setPrefRowCount(3);
        
        // 封面选择
        Label coverLabel = new Label("歌单封面:");
        
        HBox coverBox = new HBox(10);
        coverBox.setAlignment(Pos.CENTER_LEFT);
        
        // 封面预览
        ImageView coverPreview = new ImageView(new Image("static/logo.jpg"));
        coverPreview.setFitWidth(100);
        coverPreview.setFitHeight(100);
        
        // 选择文件按钮
        Button selectFileButton = new Button("选择图片");
        
        // 存储选择的文件
        final File[] selectedFile = {null};
        
        selectFileButton.setOnAction(e -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择封面图片");
            fileChooser.getExtensionFilters().addAll(
                    new FileChooser.ExtensionFilter("图片文件", "*.png", "*.jpg", "*.jpeg", "*.gif")
            );
            File file = fileChooser.showOpenDialog(dialog);
            if (file != null) {
                selectedFile[0] = file;
                coverPreview.setImage(new Image(file.toURI().toString()));
            }
        });
        
        coverBox.getChildren().addAll(coverPreview, selectFileButton);
        
        // 添加间距，确保按钮区域可见
        Region spacer = new Region();
        VBox.setVgrow(spacer, Priority.ALWAYS);
        spacer.setMinHeight(20);
        
        // 按钮区域
        HBox buttonBox = new HBox(10);
        buttonBox.setAlignment(Pos.CENTER_RIGHT);
        buttonBox.setPadding(new Insets(15, 0, 0, 0));
        
        Button cancelButton = new Button("取消");
        cancelButton.setPrefWidth(80);
        cancelButton.setOnAction(e -> dialog.close());
        
        Button createButton = new Button("创建");
        createButton.setPrefWidth(80);
        createButton.setStyle("-fx-background-color: #1db954; -fx-text-fill: white; -fx-font-weight: bold;");
        createButton.setOnAction(e -> {
            // 验证输入
            if (nameField.getText().trim().isEmpty()) {
                showAlert("错误", "请输入歌单名称");
                return;
            }
            
            if (descArea.getText().trim().isEmpty()) {
                showAlert("错误", "请输入歌单描述");
                return;
            }
            
            if (selectedFile[0] == null) {
                showAlert("错误", "请选择歌单封面");
                return;
            }
            
            // 创建歌单请求对象
            PlaylistReq playlistReq = new PlaylistReq()
                    .setName(nameField.getText().trim())
                    .setDescription(descArea.getText().trim())
                    .setCoverFile(selectedFile[0]);
            
            // 调用后端创建歌单
            new Thread(() -> {
                try {
                    Result<PlaylistResp> result = playlistController.add(playlistReq);
                    
                    Platform.runLater(() -> {
                        if (result.isSuccess()) {
                            // 关闭对话框
                            dialog.close();
                            
                            // 显示成功消息
                            showAlert("成功", "歌单创建成功");
                            
                            // 刷新歌单列表
                            loadPlaylistsInBackground();
                            
                            // 通知外部刷新
                            if (playlistRefreshCallback != null) {
                                playlistRefreshCallback.onPlaylistRefresh();
                            }
                        } else {
                            showAlert("错误", "歌单创建失败: " + result.getMessage());
                        }
                    });
                } catch (Exception ex) {
                    Platform.runLater(() -> {
                        showAlert("错误", "歌单创建失败: " + ex.getMessage());
                    });
                    log.error("创建歌单失败", ex);
                }
            }).start();
        });
        
        buttonBox.getChildren().addAll(cancelButton, createButton);
        
        content.getChildren().addAll(
                nameLabel, nameField,
                descLabel, descArea,
                coverLabel, coverBox,
                spacer,
                new Separator(),
                buttonBox
        );
        
        Scene scene = new Scene(content);
        dialog.setScene(scene);
        dialog.showAndWait();
    }
    
    /**
     * 显示提示对话框
     */
    private void showAlert(String title, String message) {
        // 只有错误消息使用标准Alert
        if (title.equals("错误")) {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle(title);
            alert.setHeaderText(null);
            alert.setContentText(message);
            alert.showAndWait();
        } else {
            // 成功消息使用自定义美化的提示
            showSuccessNotification(message);
        }
    }
    
    /**
     * 显示美化的成功提示
     */
    private void showSuccessNotification(String message) {
        Stage notificationStage = new Stage();
        notificationStage.initModality(Modality.NONE);
        notificationStage.setTitle("提示");
        notificationStage.setResizable(false);
        
        // 创建通知内容
        VBox content = new VBox();
        content.setAlignment(Pos.CENTER);
        content.setSpacing(15);
        content.setPadding(new Insets(20));
        content.setMinWidth(300);
        content.setMinHeight(150);
        content.setStyle("-fx-background-color: linear-gradient(to bottom right, #ffffff, #f8f8f8); -fx-background-radius: 10px;");
        
        // 成功图标
        ImageView successIcon = new ImageView(new Image("static/success-icon.png", 50, 50, true, true));
        
        // 成功消息
        Label messageLabel = new Label(message);
        messageLabel.setStyle("-fx-font-size: 16px; -fx-font-weight: bold; -fx-text-fill: #1db954;");
        
        // 描述文本
        Label descLabel = new Label("您的歌单已成功创建，可以开始添加音乐了!");
        descLabel.setStyle("-fx-font-size: 14px; -fx-text-fill: #666666;");
        
        // 按钮
        Button okButton = new Button("确定");
        okButton.setPrefWidth(100);
        okButton.setStyle(
                "-fx-background-color: #1db954; " +
                "-fx-text-fill: white; " +
                "-fx-font-weight: bold; " +
                "-fx-padding: 8px 15px; " +
                "-fx-background-radius: 20px;"
        );
        
        okButton.setOnAction(e -> {
            notificationStage.close();
        });
        
        content.getChildren().addAll(successIcon, messageLabel, descLabel, okButton);
        
        // 添加阴影效果
        content.setEffect(new javafx.scene.effect.DropShadow(10, javafx.scene.paint.Color.rgb(0, 0, 0, 0.2)));
        
        Scene scene = new Scene(content);
        scene.setFill(javafx.scene.paint.Color.TRANSPARENT);
        
        notificationStage.setScene(scene);
        notificationStage.initStyle(javafx.stage.StageStyle.TRANSPARENT);
        
        // 获取屏幕尺寸并居中显示
        javafx.geometry.Rectangle2D screenBounds = javafx.stage.Screen.getPrimary().getVisualBounds();
        
        // 设置位置（直接调用show而不是showAndWait，避免阻塞UI线程）
        notificationStage.show();
        
        // 窗口显示后调整位置
        double centerX = screenBounds.getMinX() + (screenBounds.getWidth() - notificationStage.getWidth()) / 2;
        double centerY = screenBounds.getMinY() + (screenBounds.getHeight() - notificationStage.getHeight()) / 2;
        notificationStage.setX(centerX);
        notificationStage.setY(centerY);
        
        // 自动消失计时器
        Timeline timeline = new Timeline(new KeyFrame(
                Duration.seconds(3),
                event -> notificationStage.close()
        ));
        timeline.setCycleCount(1);
        timeline.play();
        
        // 注意: 通知窗口已在前面显示，不需要再次调用show或showAndWait
        // notificationStage.showAndWait(); // 已被移除
    }
    
    /**
     * 歌单选择回调接口
     */
    public interface PlaylistSelectedCallback {
        void onPlaylistSelected(PlaylistResp playlist);
        
        /**
         * 当选择歌曲时回调
         * @param song 选中的歌曲
         */
        void onSongSelected(SongsResp song);
    }
    
    /**
     * 歌单列表刷新回调接口
     */
    public interface PlaylistRefreshCallback {
        void onPlaylistRefresh();
    }

    // 添加公共方法，使外部可以调用显示指定歌单
    /**
     * 公共方法：显示指定的歌单详情
     * @param playlist 要显示的歌单
     */
    public void showPlaylistDetail(PlaylistResp playlist) {
        // 如果传入的歌单不为空，则更新当前选中的歌单
        if (playlist != null) {
            // 设置标志位为false，防止自动加载第一个歌单
            autoLoadFirstPlaylist = false;
            
            currentPlaylist = playlist;
            
            // 显示歌单详情
            showPlaylistDetailInternal(playlist);
        }
    }

    // 已移除toggleCollectPlaylist方法，因为收藏功能已在"发现歌单"页面实现

    // 已移除checkPlaylistCollectionStatus方法，因为收藏功能已在"发现歌单"页面实现
} 